import React, { useEffect, useRef, useState } from 'react';
import { Card, List, Input, Button, Avatar, Space, Badge, Empty, Modal, Row, Col, Tag, Select } from 'antd';
import { SendOutlined, UserOutlined, TeamOutlined, PlusOutlined, SearchOutlined, LockOutlined, CheckCircleOutlined, MessageOutlined } from '@ant-design/icons';
import './ChatRoom.scss';

interface Message {
  id: string;
  user: string;
  avatar?: string;
  content: string;
  time: string;
  self?: boolean;
}

interface JoinedRoom {
  id: string;
  name: string;
  description?: string;
  category: '学习' | '生活' | '兴趣' | '校内通知';
  online: number;
  unread?: number;
  lastMessage?: string;
  lastTime?: string;
}

interface AllChatRoom {
  id: string;
  name: string;
  description?: string;
  type: 'open' | 'approval' | 'closed';
  category: '学习' | '生活' | '兴趣' | '校内通知';
  online: number;
  joined?: boolean;
}

const { Search } = Input;
const { Option } = Select;

const ChatRoom: React.FC = () => {
  const [selectedRoomId, setSelectedRoomId] = useState<string>('1');
  const [messages, setMessages] = useState<Message[]>([]);
  const [text, setText] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [keyword, setKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<'all' | AllChatRoom['type']>('all');
  const [categoryFilter, setCategoryFilter] = useState<'all' | AllChatRoom['category']>('all');
  const listRef = useRef<HTMLDivElement>(null);

  // 已加入的聊天室
  const joinedRooms: JoinedRoom[] = [
    { id: '1', name: '前端学习交流', description: 'React/TypeScript/工程化', category: '学习', online: 128, unread: 3, lastMessage: '有没有人用过vite?', lastTime: '10:30' },
    { id: '2', name: '算法刷题小组', description: '每日一题，打卡交流', category: '学习', online: 56, lastMessage: '今天的题目好难', lastTime: '09:15' },
    { id: '3', name: '二手好价情报', description: '全网好价，白菜价速报', category: '生活', online: 203, unread: 12, lastMessage: '京东有优惠券', lastTime: '昨天' },
  ];

  // 所有聊天室（弹窗中显示）
  const allRooms: AllChatRoom[] = [
    { id: '1', name: '前端学习交流', description: 'React/TypeScript/工程化', type: 'open', category: '学习', online: 128, joined: true },
    { id: '2', name: '算法刷题小组', description: '每日一题，打卡交流', type: 'approval', category: '学习', online: 56, joined: true },
    { id: '3', name: '二手好价情报', description: '全网好价，白菜价速报', type: 'open', category: '生活', online: 203, joined: true },
    { id: '4', name: '摄影与后期', description: '器材讨论与作品分享', type: 'approval', category: '兴趣', online: 78, joined: false },
    { id: '5', name: '校内通知公告', description: '教务处/学生处官方通知', type: 'closed', category: '校内通知', online: 1024, joined: false },
    { id: '6', name: 'Java后端技术', description: 'Spring Boot/MyBatis', type: 'open', category: '学习', online: 95, joined: false },
    { id: '7', name: '健身打卡', description: '健康生活，一起运动', type: 'open', category: '生活', online: 67, joined: false },
  ];

  const filteredAllRooms = allRooms.filter((r) => {
    const matchKeyword = keyword ? (r.name.includes(keyword) || (r.description || '').includes(keyword)) : true;
    const matchType = typeFilter === 'all' ? true : r.type === typeFilter;
    const matchCategory = categoryFilter === 'all' ? true : r.category === categoryFilter;
    return matchKeyword && matchType && matchCategory;
  });

  useEffect(() => {
    // 模拟加载历史消息
    setMessages([
      { id: '1', user: '张三', content: '大家好，欢迎加入聊天室', time: '10:00' },
      { id: '2', user: '李四', content: '请文明发言，遵守规则～', time: '10:01' },
      { id: '3', user: '我', content: '收到！', time: '10:02', self: true },
    ]);
  }, [selectedRoomId]);

  useEffect(() => {
    // 滚动到底部
    listRef.current?.scrollTo({ top: listRef.current.scrollHeight, behavior: 'smooth' });
  }, [messages]);

  const send = () => {
    if (!text.trim()) return;
    const now = new Date();
    setMessages((prev) => [
      ...prev,
      {
        id: String(prev.length + 1),
        user: '我',
        content: text.trim(),
        time: `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`,
        self: true,
      },
    ]);
    setText('');
  };

  const typeTag = (type: AllChatRoom['type']) => {
    switch (type) {
      case 'open':
        return <Tag color="green" icon={<CheckCircleOutlined />}>可直接加入</Tag>;
      case 'approval':
        return <Tag color="gold" icon={<LockOutlined />}>需审核加入</Tag>;
      case 'closed':
        return <Tag color="red" icon={<LockOutlined />}>不可加入</Tag>;
    }
  };

  const handleJoinRoom = (room: AllChatRoom) => {
    if (room.joined) {
      setModalVisible(false);
      setSelectedRoomId(room.id);
      return;
    }
    if (room.type === 'closed') return;
    // 模拟加入聊天室
    alert(`${room.type === 'approval' ? '已提交加入申请，等待审核' : '成功加入聊天室：' + room.name}`);
    if (room.type === 'open') {
      setModalVisible(false);
      setSelectedRoomId(room.id);
    }
  };

  const selectedRoom = joinedRooms.find(r => r.id === selectedRoomId);

  return (
    <div className="chat-room-page">
      <div className="chat-container">
        {/* 左侧：已加入的聊天室列表 */}
        <div className="rooms-sidebar">
          <div className="sidebar-header">
            <h2>我的聊天室</h2>
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={() => setModalVisible(true)}
            >
              加入
            </Button>
          </div>
          <div className="rooms-list">
            {joinedRooms.map((room) => (
              <div
                key={room.id}
                className={`room-item ${selectedRoomId === room.id ? 'active' : ''}`}
                onClick={() => setSelectedRoomId(room.id)}
              >
                <Badge count={room.unread} size="small">
                  <Avatar size={48} icon={<TeamOutlined />} style={{ background: '#1890ff' }} />
                </Badge>
                <div className="room-info">
                  <div className="room-name">{room.name}</div>
                  <div className="room-last-msg">
                    {room.lastMessage || room.description}
                  </div>
                </div>
                <div className="room-meta">
                  <div className="room-time">{room.lastTime}</div>
                  <div className="room-online">
                    <TeamOutlined /> {room.online}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 右侧：聊天内容区域 */}
        <div className="chat-content">
          {selectedRoom ? (
            <Card className="chat-card">
              <div className="chat-header">
                <div className="header-info">
                  <h2>{selectedRoom.name}</h2>
                  <Space size="small">
                    <Tag color="purple">{selectedRoom.category}</Tag>
                    <span className="online-info">
                      <TeamOutlined /> {selectedRoom.online} 人在线
                    </span>
                  </Space>
                </div>
              </div>
              <div className="messages" ref={listRef as any}>
                <List
                  dataSource={messages}
                  renderItem={(msg) => (
                    <List.Item className={`msg ${msg.self ? 'self' : ''}`}>
                      <List.Item.Meta
                        avatar={<Avatar icon={<UserOutlined />} />}
                        title={
                          <Space size="small">
                            <span className="user">{msg.user}</span>
                            <span className="time">{msg.time}</span>
                          </Space>
                        }
                        description={<div className="bubble">{msg.content}</div>}
                      />
                    </List.Item>
                  )}
                />
              </div>
              <div className="composer">
                <Input.TextArea
                  value={text}
                  onChange={(e) => setText(e.target.value)}
                  placeholder="输入消息，按Enter发送，Shift+Enter换行"
                  autoSize={{ minRows: 1, maxRows: 4 }}
                  onPressEnter={(e) => {
                    if (!e.shiftKey) {
                      e.preventDefault();
                      send();
                    }
                  }}
                />
                <Button type="primary" icon={<SendOutlined />} onClick={send} disabled={!text.trim()}>
                  发送
                </Button>
              </div>
            </Card>
          ) : (
            <Empty description="请选择一个聊天室开始聊天" />
          )}
        </div>
      </div>

      {/* 弹窗：所有聊天室 */}
      <Modal
        title="浏览所有聊天室"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={1000}
        className="chat-rooms-modal"
      >
        <div className="modal-filters">
          <Space size="middle" wrap>
            <Search
              placeholder="搜索房间名称或简介..."
              allowClear
              onSearch={setKeyword}
              prefix={<SearchOutlined />}
              style={{ width: 300 }}
            />
            <Select value={typeFilter} style={{ width: 140 }} onChange={(v) => setTypeFilter(v)}>
              <Option value="all">全部类型</Option>
              <Option value="open">可直接加入</Option>
              <Option value="approval">需审核加入</Option>
              <Option value="closed">无法加入</Option>
            </Select>
            <Select value={categoryFilter} style={{ width: 140 }} onChange={(v) => setCategoryFilter(v)}>
              <Option value="all">全部分类</Option>
              <Option value="学习">学习</Option>
              <Option value="生活">生活</Option>
              <Option value="兴趣">兴趣</Option>
              <Option value="校内通知">校内通知</Option>
            </Select>
          </Space>
        </div>

        <div className="modal-rooms-grid">
          {filteredAllRooms.length === 0 ? (
            <Empty description="暂无符合条件的聊天室" />
          ) : (
            <Row gutter={[16, 16]}>
              {filteredAllRooms.map((room) => (
                <Col xs={24} sm={12} lg={8} key={room.id}>
                  <Card
                    hoverable
                    className="room-card"
                    onClick={() => handleJoinRoom(room)}
                  >
                    <div className="room-header">
                      <div className="room-icon">
                        <TeamOutlined style={{ fontSize: 40, color: '#1890ff' }} />
                      </div>
                    </div>
                    
                    <div className="room-content">
                      <h3 className="room-name">{room.name}</h3>
                      
                      <div className="room-tags">
                        {typeTag(room.type)}
                        <Tag color="purple">{room.category}</Tag>
                        {room.joined && <Tag color="blue">已加入</Tag>}
                      </div>
                      
                      <p className="room-description">{room.description || '暂无简介'}</p>
                      
                      <div className="room-footer">
                        <div className="online-count">
                          <TeamOutlined /> {room.online} 人在线
                        </div>
                      </div>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default ChatRoom;
